<?php

class UPLOAD
{

    public $datetime;   //随机数
    public $photp_path = "../upload/";    //上传文件存放路径
    public $photo_name;   //上传图片文件名
    public $photo_tmp_name;    //图片临时文件名
    public $photo_type;   //图片类型
    public $all_photo_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif', 'image/bmp');    //允许上传图片类型
    public $phpto_size;   //图片大小
    public $all_photo_size = 2097152;   //允许上传文件大小

    function __construct()
    {
        $this->datetime = date("YmdHis");
    }

    //获取文件类型
    function get_type($type)
    {
        $this->photo_type = $type;
    }

    //获取文件大小
    function get_size($size)
    {
        $this->phpto_size = $size . "<br>";
    }

    //获取上传临时文件名
    function get_tmp_name($tmp_name)
    {
        $this->photo_tmp_name = $tmp_name;
        $this->imgsize = getimagesize($tmp_name);
    }

    //获取原文件名
    function get_name($name, $random = TRUE)
    {
        if ($random)
        {
            $this->photo_name = $this->photp_path . $this->datetime . strrchr($name, "."); //strrchr获取文件的点最后一次出现的位置
        } else
        {
            $this->photo_name = $this->photp_path . $name . '.jpg'; //strrchr获取文件的点最后一次出现的位置
        }
        return $this->photo_name;
    }

    function get_filepath()
    {
        return substr($this->photo_name, 3);
    }

    //判断上传文件存放目录
    function check_path()
    {
        if (!file_exists($this->photp_path))
        {
            mkdir($this->photp_path);
        }
    }

    //判断上传文件是否超过允许大小
    function check_size()
    {
        if ($this->phpto_size > $this->all_photo_size)
        {
            $this->showerror("上传图片超过2M");
        }
    }

    //判断文件类型
    function check_type()
    {
        if (!in_array($this->photo_type, $this->all_photo_type))
        {
            $this->showerror("上传图片类型错误");
        }
    }

    //上传图片
    function upload_photo()
    {
        if (!move_uploaded_file($this->photo_tmp_name, $this->photo_name))
        {
            $this->showerror("上传文件出错");
        }
    }

    //错误提示
    function showerror($errorstr)
    {
        echo "<script language=javascript>alert('$errorstr');location='javascript:history.go(-1);';</script>";
        exit();
    }

    function upload_run()
    {
        $this->check_path();
        $this->check_size();
        $this->check_type();
        $this->upload_photo();
    }

}

?>